// 使用 useState 做状态管理
import nuxtApi from '~/apis/nuxt-api.js'
export function useUserInfo() {

  const info = useState('info', () => {
    if (!useCookie('userInfo').value) {
      return {}
    }
    return useCookie('userInfo')
  })

  const token = useState('token', () => useCookie('token'))

  function logout() {
    info.value = {}
    token.value = undefined
    const tk = useCookie('token')
    tk.value = token.value
  }

  function login(val) {
    return new Promise(async (resolve, reject) => {
      const { data } = await nuxtApi.login(val)
      info.value = data.value
      const userInfo = useCookie('userInfo')
      userInfo.value = data.value
      token.value = data.value.token
      const tk = useCookie('token')
      tk.value = token.value
      resolve()
    })
  }
  return {
    info,
    token,
    login,
    logout,
  }
}
